package com.example.codeservice.service;

import com.example.codeservice.dao.AuthCodeDao;
import com.example.codeservice.pojo.AuthCode;
import com.example.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * @author zhouyp
 * @program example-parent
 * @description
 * @create 2020-07-27
 */
@Service
@org.apache.dubbo.config.annotation.Service
public class CodeServiceImpl implements CodeService {

	private static final Random RANDOM = new Random();

	@Autowired
	private AuthCodeDao authCodeDao;

	@Override
	public String createCode(String email) {
		final String randomCode = RANDOM.nextInt(1000000) + 1 + "";

		final Calendar nowTime = Calendar.getInstance();
		final Date date = nowTime.getTime();
		nowTime.add(Calendar.MINUTE, 10);
		final Date expiretDate = nowTime.getTime();

		final AuthCode authCode = new AuthCode();
		authCode.setEmail(email);
		authCode.setCode(randomCode);
		authCode.setCreatetime(date);
		authCode.setExpiretime(expiretDate);
		authCodeDao.save(authCode);
		return randomCode;
	}

	/**
	 * 校验验证码是否正确，0正确1错误2超时
	 *
	 * @return int
	 */
	@Override
	public int validate(String email, String code) {
		final AuthCode lagouAuthCode = authCodeDao
				.findFirstByEmailOrderByCreatetimeDesc(email);

		if (null == lagouAuthCode) {
			System.out.println("==========没找到该邮箱匹配的用户==========");
			return 1;
		}

		if (!lagouAuthCode.getCode().equals(code)) {
			System.out.println("==========验证码错误==========");
			return 1;
		}
		Date expiretime = lagouAuthCode.getExpiretime();
		Date nowDate = new Date();
		if (nowDate.after(expiretime)) {
			System.out.println("==========验证码超时==========");
			return 2;
		}
		return 0;
	}

}
